<?php
class UsersController extends AppController {
	var $name = 'Users';
	var $uses = array('User', 'Group', 'Permission', 'PermissionGroup');
	var $layout = 'admin';
	var $helpers = array('Html', 'Javascript', 'Form', 'Time', 'Tinymce');
	var $components = array('Auth');
	var $paginate = array(
						'fields' => array('User.id', 'User.username'),
						'limit' => 5,
	 					'order' => array('User.id' => 'asc')
						);
	
	function beforeFilter()
	{
		parent::beforeFilter();
		
		$this->Auth->allow('helloUser'); // allow everybody access/ comment it for permission implement
		
		//$this->Auth->allow('redirectLogin');
		//Change the default error message displayed when someone does not successfully log in.
		$this->Auth->loginError = "Tài khoản hoặc mật khẩu chưa đúng. Xin mời bạn hãy nhập lại!";
	}
	
	function index() {
		$this->User->recursive = 0;
		$data = $this->paginate('User');
		$this->set('data', $data);
	}
	/*
	 * Add users
	 */
	function add()
	{
		if (!empty($this->data))
		{
			if ($this->User->save($this->data))
			{
				$this->Session->setFlash('Đã thêm người dùng');
				$this->redirect($this->referer());
			} else {
				$this->Session->setFlash('Lỗi trong quá trình lưu dữ liệu');
			}
		}
		//Get list group
		$this->set('groups',$this->User->Group->find('list'));
	}
	
	/*
	 * edit user information 
	 * 
	 */
	function edit($id = null)
	{
		if(! $id && empty ($this->data))
		{
			$this->Session->setFlash (__ ('Invalid User', true));
			$this->redirect (array('action' => 'index'));
		}
		if(! empty ($this->data))
		{
			if($this->User->save ($this->data))
			{
				$this->Session->setFlash (__ ('The User has been saved', true));
				$this->redirect (array('action' => 'index'));
			}else
			{
				$this->Session->setFlash (__ ('The User could not be saved. Please, try again.', true));
			}
		}
		if(empty ($this->data))
		{
			$this->data = $this->User->read (null, $id);
		}
		$groups = $this->User->Group->find ('list');
		$this->set (compact ('groups'));
	}
	
	/*
	 * Delete user
	 */
	
	function delete($id = null)
	{
		if(! $id)
		{
			$this->Session->setFlash (__ ('Invalid id for User', true));
			$this->redirect (array('action' => 'index'));
		}
		if($this->User->del ($id))
		{
			$this->Session->setFlash (__ ('User deleted', true));
			$this->redirect (array('action' => 'index'));
		}
	}
	
	/*
	 * Login logout
	 */
	function login()
	{
		$this->layout = 'login';
	}
	function logout()
	{
		$this->Session->del ('Permissions');
		$this->redirect ($this->Auth->logout());
	}
	function helloUser()
	{
		$user = $this->Auth->user();
		//debug($user);die();
		if (isset($this->params['requested'])) {
			return $user;
		}
	}
}
?>
